/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servletStudent;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sessionbean.AccountFacadeLocal;
import sessionbean.AssignmentFacadeLocal;
import sessionbean.StudentProfileFacadeLocal;
import sessionbean.StudentResultFacadeLocal;
import supportlearning.entities.Account;
import supportlearning.entities.StudentResult;
import supportlearning.entities.StudentResultPK;

/**
 *
 * @author Huy
 */
public class servletStudents extends HttpServlet {

    @EJB
    private StudentResultFacadeLocal studentResultFacade;
    @EJB
    private StudentProfileFacadeLocal studentProfileFacade;
    @EJB
    private AssignmentFacadeLocal assignmentFacade;
    @EJB
    private AccountFacadeLocal accountFacade;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession sess = request.getSession();
            String action = request.getParameter("action");
            if (action.equals("Profile")) {
                String id = request.getParameter("id");
                Account acc = accountFacade.find(id.trim());
                request.setAttribute("accobj", acc);
                request.getRequestDispatcher("StudentProfile.jsp").forward(request, response);
            } else if (action.equals("Edit")) {
                String id = request.getParameter("stuid");
                Account acc = accountFacade.find(id.trim());
                request.setAttribute("accobj", acc);
                request.getRequestDispatcher("updateStudentProfile.jsp").forward(request, response);
            } else if (action.equals("Update")) {
                String id = request.getParameter("stuid");
                Account acc = accountFacade.find(id.trim());
                String fname = request.getParameter("txtfirstname");
                String lname = request.getParameter("txtlastname");
                String address = request.getParameter("txtaddress");
                String email = request.getParameter("txtemail");
                acc.setFirstName(fname);
                acc.setLastName(lname);
                acc.setAddress(address);
                acc.setEmail(email);
                accountFacade.edit(acc);
                response.sendRedirect("servletStudents?action=Profile&id=" + sess.getAttribute("sessuser"));
            } else if (action.equals("uploadavatar")) {
                String contentType = request.getContentType();
                String id = request.getParameter("id");
                //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                    DataInputStream in = new DataInputStream(request.getInputStream());
                    //we are taking the length of Content type data
                    int formDataLength = request.getContentLength();
                    byte dataBytes[] = new byte[formDataLength];//du lieu file

                    int byteRead = 0;
                    int totalBytesRead = 0;
                    //this loop converting the uploaded file into byte code
                    while (totalBytesRead < formDataLength) {
                        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                        totalBytesRead += byteRead;
                    }

                    String saveFile = getServletContext().getRealPath("");
                    //saveFile ở dạng E:\javaSoft\jboss-4.2.3.GA\server\default\.\tmp\deploy\tmp1886710651506332626FileUploadDemo-exp.war
                    int idx = saveFile.lastIndexOf("\\default") + 8;
                    saveFile = saveFile.substring(0, idx);
                    out.println(saveFile + "<br/>");
//                for (int i = 0; i < 3; i++) {
//                    saveFile = saveFile.substring(0, saveFile.lastIndexOf("\\"));
//                }
                    String file = new String(dataBytes);
                    //lay file name
                    String filename = file.substring(file.indexOf("filename=\"") + 10);
                    filename = filename.substring(0, filename.indexOf("\n"));
                    filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.indexOf("\""));

                    //duong dan đầy đủ
                    saveFile = saveFile.replace("\\", "/");
                    saveFile += "/deploy/student.war/" + filename;

                    out.println(saveFile);

                    int lastIndex = contentType.lastIndexOf("=");
                    String boundary = contentType.substring(lastIndex + 1, contentType.length());
                    int pos;
                    //extracting the index of file
                    pos = file.indexOf("filename=\"");
                    pos = file.indexOf("\n", pos) + 1;
                    pos = file.indexOf("\n", pos) + 1;
                    pos = file.indexOf("\n", pos) + 1;
                    int boundaryLocation = file.indexOf(boundary, pos) - 4;
                    int startPos = ((file.substring(0, pos)).getBytes()).length;
                    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                    // creating a new file with the same name and writing the content in new file
                    FileOutputStream fileOut = new FileOutputStream(saveFile);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();
                    Account acc = accountFacade.find(id);
                    acc.setAvatar("http://localhost:8080/student/" + filename);
                    accountFacade.edit(acc);
                    response.sendRedirect("servletStudents?action=Profile&id=" + sess.getAttribute("sessuser"));

                }
            } else if (action.equals("UploadAss")) {
                String contentType = request.getContentType();
                int id = Integer.parseInt(request.getParameter("assid"));
                String stuid = (String) sess.getAttribute("sessuser");
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                    DataInputStream in = new DataInputStream(request.getInputStream());
                    //we are taking the length of Content type data
                    int formDataLength = request.getContentLength();
                    byte dataBytes[] = new byte[formDataLength];//du lieu file

                    int byteRead = 0;
                    int totalBytesRead = 0;
                    //this loop converting the uploaded file into byte code
                    while (totalBytesRead < formDataLength) {
                        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                        totalBytesRead += byteRead;
                    }

                    String saveFile = getServletContext().getRealPath("");
                    //saveFile ở dạng E:\javaSoft\jboss-4.2.3.GA\server\default\.\tmp\deploy\tmp1886710651506332626FileUploadDemo-exp.war
                    int idx = saveFile.lastIndexOf("\\default") + 8;
                    saveFile = saveFile.substring(0, idx);
                    out.println(saveFile + "<br/>");
//                for (int i = 0; i < 3; i++) {
//                    saveFile = saveFile.substring(0, saveFile.lastIndexOf("\\"));
//                }
                    String file = new String(dataBytes);
                    //lay file name
                    String filename = file.substring(file.indexOf("filename=\"") + 10);
                    filename = filename.substring(0, filename.indexOf("\n"));
                    filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.indexOf("\""));

                    //duong dan đầy đủ
                    saveFile = saveFile.replace("\\", "/");
                    saveFile += "/deploy/student.war/" + filename;

                    out.println(saveFile);

                    int lastIndex = contentType.lastIndexOf("=");
                    String boundary = contentType.substring(lastIndex + 1, contentType.length());
                    int pos;
                    //extracting the index of file
                    pos = file.indexOf("filename=\"");
                    pos = file.indexOf("\n", pos) + 1;
                    pos = file.indexOf("\n", pos) + 1;
                    pos = file.indexOf("\n", pos) + 1;
                    int boundaryLocation = file.indexOf(boundary, pos) - 4;
                    int startPos = ((file.substring(0, pos)).getBytes()).length;
                    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                    // creating a new file with the same name and writing the content in new file
                    FileOutputStream fileOut = new FileOutputStream(saveFile);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();
                    // StudentResultPK obj=new StudentResultPK(stuid, id);
                    StudentResult obj1 = new StudentResult();
                    // obj1.setStudentResultPK(obj);
                    System.out.println("StudentID and AssignmentID:" + stuid + "&" + id);
                    // obj1.setAssignment(assignmentFacade.find(id));
                    //  obj1.setStudentProfile(studentProfileFacade.find(stuid));
                    studentProfileFacade.find(stuid).getStudentResultCollection().add(obj1);
                    assignmentFacade.find(id).getStudentResultCollection().add(obj1);
                    if (obj1 != null) {
                        obj1.setSubmitDate(Calendar.getInstance().getTime());
                        obj1.setUrlFile("http://localhost:8080/student/" + filename);
                        studentResultFacade.edit(obj1);
                        out.println("Thanh Cong hoan hao.");
                    }

                    out.print("OK");


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
